<?php

namespace app\service;

//宠物服务层
use app\model\Shop;
use app\model\User;
use app\model\UserOrder;
use app\model\UserProp;

class ShopService extends Base
{

    //获取所有宠物信息
    public function list()
    {
        $shops = (new Shop())->select();
        return apiSuccess($shops);
    }

    //购买道具
    public function buy(User $user,$shop_id, $num){

        $shop = (new Shop)->find($shop_id);
        if(!$shop){
            return apiError('商品不存在');
        }

        //判断用户是否有足够的积分购买
        if ($user->score < $shop->price * $num) {
            return apiError('积分不足');
        }

        //扣除用户金币
        $user->score -= $shop->price * $num;
        $user->save();

        //增加订单
        UserOrder::create([
            'user_id' => $user->id,
            'shop_id' => $shop->id,
            'num' => $num,
            'price' => $shop->price * $num,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        //道具数量增加
        $user_prop = UserProp::where('user_id', $user->id)->where('shop_id', $shop->id)->find();
        if (!$user_prop) {
            $user_prop = UserProp::create([
                'user_id' => $user->id,
                'shop_id' => $shop->id,
                'num' => $num,
                'exp' => $shop->exp,
                'created_at' => date('Y-m-d H:i:s')
            ]);
        } else {
            $user_prop->num += $num;
            $user_prop->save();
        }
        return apiSuccess($user_prop);
    }


}